#include "pch.h"
#include "FileIO.h"

TCHAR FileIO::_savepath[MAX_PATH];
filepathlengthsize_t FileIO::_savepathlength;

TCHAR* FileIO::getSavePath()
{
	return _savepath;
}

void FileIO::setSavePath(const TCHAR spath[MAX_PATH])
{
	_tcscpy_s(_savepath, spath);
	_savepathlength = _tcslen(spath);
}

filepathlengthsize_t FileIO::getSavePathLength()
{
	return _savepathlength;
}

FileIO::~FileIO()
{
	Close();
}

void FileIO::CreateFullPath(const TCHAR path[MAX_PATH])
{
	TCHAR dpath[MAX_PATH] = { 0 }, temp[MAX_PATH] = { 0 };
	filepathlengthsize_t dpathlength = _tcslen(path);
	TCHAR* token, * nexttoken = nullptr;

	while (dpathlength && path[dpathlength] != '\\') --dpathlength;
	memcpy_s(dpath, MAX_PATH, path, dpathlength * sizeof(TCHAR));

	token = _tcstok_s(dpath, TEXT("\\"), &nexttoken);
	while (token)
	{
		_tcscpy_s(temp + _tcslen(temp), MAX_PATH - _tcslen(temp), token);
		if (-1 == _taccess(temp, 0))
		{
			CreateDirectory(temp, NULL);
		}
		token = _tcstok_s(nexttoken, TEXT("\\"), &nexttoken);
		_tcscpy_s(temp + _tcslen(temp), MAX_PATH - _tcslen(temp), TEXT("\\"));
	}
}

int FileIO::Open_Sender(const FileInfo* pfi)
{
	_tfopen_s(&_fp, pfi->absolutepath, TEXT("rb"));
	if (!_fp)
	{
		return 1;
	}
	return 0;
}

int FileIO::Open_Receiver(FileInfo* pfi)
{
	_tcscpy_s(pfi->absolutepath, _savepath);
	_tcscpy_s(pfi->absolutepath + _savepathlength, MAX_PATH - _savepathlength, pfi->relativepath);
	CreateFullPath(pfi->absolutepath);
	_tfopen_s(&_fp, pfi->absolutepath, TEXT("wb"));
	if (!_fp)
	{
		return 1;
	}
	return 0;
}

int FileIO::Read(void* buff, int bytecount)
{
	/*
	if (bytecount >= 0x100000000)
	{
	}
	*/
	return fread(buff, sizeof(BYTE), bytecount, _fp);
}

int FileIO::Write(void* buff, int bytecount)
{
	if (!_fp)
	{
		return bytecount;
	}
	return fwrite(buff, sizeof(BYTE), bytecount, _fp);
}

void FileIO::Close()
{
	if (_fp)
	{
		fclose(_fp);
		_fp = nullptr;
	}
}
